package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.MeltCloudGroup;
import com.yami.shop.bean.model.MeltCloudGroupUser;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.service.MeltCloudGroupService;
import com.yami.shop.service.MeltCloudGroupUserService;
import com.yami.shop.util.SendUtil;
import io.rong.RongCloud;
import io.rong.methods.group.mute.MuteAllMembers;
import io.rong.methods.ultragroup.ban.Ban;
import io.rong.models.Result;
import io.rong.models.response.GroupMuteAllMembersCheckResult;
import io.rong.models.response.GroupMuteAllMembersListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

import static com.yami.shop.common.response.ServerResponseEntity.success;

/**
 * 群组禁言
 */
@Service
@Slf4j
public class RongYunAllMembersServiceImpl {

    @Autowired
    private RongCloud rongCloud;

    private MuteAllMembers muteAllMembers;
    
    private Ban ban;

    @Autowired
    private MeltCloudGroupService groupService;

    @Autowired
    private MeltCloudGroupUserService groupUserService;

    @PostConstruct
    public void init() {
        muteAllMembers = rongCloud.group.muteAllMembers;
        ban = rongCloud.ultraGroup.ban;
    }


    /**
     * 添加禁言群方法
     *
     * @param groupIds
     * @return
     */
    @Transactional
    public ServerResponseEntity<String> muteAllMembersAdd(List<String> groupIds) throws Exception {
        // 1. 修改群组禁言状态
        List<MeltCloudGroup> groupList = groupService.listByIds(groupIds);
        List<MeltCloudGroupUser> groupUsers = Lists.newArrayList();
        List<String> ultraGroupIds = new ArrayList<>();
        for (MeltCloudGroup meltCloudGroup : groupList) {
            meltCloudGroup.setGroupStatus("1");
            LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                    .eq(MeltCloudGroupUser::getGroupId, meltCloudGroup.getId());
            List<MeltCloudGroupUser> list = groupUserService.list(eq);
            if (meltCloudGroup.getType().equals("1")) {
                ultraGroupIds.add(String.valueOf(meltCloudGroup.getId()));
            }
            groupUsers.addAll(list);
        }
        groupService.updateBatchById(groupList);

        // 2.修改群成员状态
        groupUsers.forEach(user -> user.setUserStatus("1"));
        groupUserService.updateBatchById(groupUsers);

        // 3. 同步融云禁言
        groupIds.removeAll(ultraGroupIds);
        for (String ultraGroupId : ultraGroupIds) {
            Result result = ban.set(ultraGroupId, true);
            if (SendUtil.requestError(result))
                throw new YamiShopBindException("超级群禁言异常:" + result.getErrorMessage());
        }
        if (groupIds.size() > 0) {
            String[] groups = groupIds.toArray(new String[groupIds.size()]);
            Result result = muteAllMembers.add(groups);
            if (SendUtil.requestSuccess(result)) return success();
            throw new YamiShopBindException("禁言群异常:" + result.getErrorMessage());
        }
        return success();
    }

    /**
     * 移除禁言群方法
     *
     * @param groupIds
     * @return
     */
    @Transactional
    public ServerResponseEntity<String> muteAllMembersRemove(List<String> groupIds) throws Exception {
        // 1. 修改群组禁言状态
        List<MeltCloudGroup> groupList = groupService.listByIds(groupIds);
        List<MeltCloudGroupUser> groupUsers = Lists.newArrayList();
        List<String> ultraGroupIds = new ArrayList<>();
        for (MeltCloudGroup meltCloudGroup : groupList) {
            meltCloudGroup.setGroupStatus("0");
            if (meltCloudGroup.getType().equals("1")) {
                ultraGroupIds.add(String.valueOf(meltCloudGroup.getId()));
            }
            LambdaQueryWrapper<MeltCloudGroupUser> eq = new LambdaQueryWrapper<MeltCloudGroupUser>()
                    .eq(MeltCloudGroupUser::getGroupId, meltCloudGroup.getId());
            List<MeltCloudGroupUser> list = groupUserService.list(eq);
            groupUsers.addAll(list);
        }
        groupService.updateBatchById(groupList);

        // 2.修改群成员状态
        groupUsers.forEach(user -> user.setUserStatus("0"));
        groupUserService.updateBatchById(groupUsers);

        // 3. 解除群组戒烟同步融云
        groupIds.removeAll(ultraGroupIds);
        for (String ultraGroupId : ultraGroupIds) {
            Result result = ban.set(ultraGroupId, false);
            if (SendUtil.requestError(result))
                throw new YamiShopBindException("超级群解除禁言异常:" + result.getErrorMessage());
        }
        if (groupIds.size() > 0) {
            String[] groups = groupIds.toArray(new String[groupIds.size()]);
            Result result = muteAllMembers.remove(groups);
            if (SendUtil.requestSuccess(result))
                return success();
            throw new YamiShopBindException("移除禁言群异常:" + result.getErrorMessage());
        }
        return success();
    }

    /**
     * 查询所有设置禁言群方法
     *
     * @return
     */
    public ServerResponseEntity<GroupMuteAllMembersListResult> muteAllMembersGetList() throws Exception {
        GroupMuteAllMembersListResult result = (GroupMuteAllMembersListResult) muteAllMembers.getList();
        if (SendUtil.requestSuccess(result))
            return success(result);
        throw new YamiShopBindException("查询所有禁言群方法异常:" + result.getErrorMessage());
    }

    /**
     * 检查禁言群方法
     *
     * @param groupIds
     * @return
     */
    public ServerResponseEntity<GroupMuteAllMembersCheckResult> muteAllMembersCheck(List<String> groupIds) throws Exception {
        String[] groups = groupIds.toArray(new String[groupIds.size()]);
        GroupMuteAllMembersCheckResult result = (GroupMuteAllMembersCheckResult) muteAllMembers.check(groups);
        if (SendUtil.requestSuccess(result))
            return success(result);
        throw new YamiShopBindException("检查禁言群方法异常：" + result.getErrorMessage());
    }


}
